package com.toannv.handler;

import java.util.List;

import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import com.toannv.card.card;
import com.toannv.definitions.KeyObjectId;
import com.toannv.definitions.ResponseId;
import com.toannv.extension.RoomExtension;
import com.toannv.gameController.CheckU;
import com.toannv.helper.Roomhelper;

public class BocBaiHandler extends BaseClientRequestHandler{

	@Override
	public void handleClientRequest(User sender, ISFSObject paras) {
		// TODO Auto-generated method stub
		int idSender = sender.getPlayerId();
		
		if(idSender == RoomExtension.UserRunning){
			card ThisCard = RoomExtension.card.pop();
			//tao doi tuong SFSObject quan bai
			SFSObject sfsO = new SFSObject();
			sfsO.putInt(KeyObjectId.CARD_NUMBER, ThisCard.getNumber());
			sfsO.putInt(KeyObjectId.CARD_POKER, ThisCard.getPoker());
			
			for(int i=0; i<RoomExtension.CardOfUser[idSender].length; i++){
				//neu co phan tu nao cua mang co number = 0 thi set gia tri moi
				if(RoomExtension.CardOfUser[idSender][i].getNumber() == 0){
					RoomExtension.CardOfUser[idSender][i].setNumber(ThisCard.getNumber());
					RoomExtension.CardOfUser[idSender][i].setPoker(ThisCard.getPoker());
					break;
				}
				//neu card la null thi tao card moi
				else if(RoomExtension.CardOfUser[idSender][i]==null){
					RoomExtension.CardOfUser[idSender][i] = new card(ThisCard);
					break;
				}
			}
			
			//tạo đối tượng phòng chơi hiện tại
			Room CurrentRoom = Roomhelper.getCurrentRoom(this);
			//danh sách người chơi ở trong phòng
			List<User> user = CurrentRoom.getUserList();
			
			card Cards[] = new card[10];
			for(int i=0; i<10; i++){
				Cards[i] = new card(RoomExtension.CardOfUser[idSender][i]);
			}
			
			int check = 0;
			check = CheckU.checkall(idSender, Cards);
			SFSObject sfsONull = new SFSObject();
			
			if(check==2){
				send(ResponseId.U_THUONG, sfsONull, sender);
			}
			else if(check==4){
				send(ResponseId.U_TRON, sfsONull, sender);
			}
			
			//gui cac doi tuong cho nguoi choi
			send(ResponseId.BOC_BAI_NULL, sfsONull, user);
			send(ResponseId.BOC_BAI, sfsO, sender);
		}
	}

}
